package com.gjy.disruptor.uuid.newd.dis;

import com.lmax.disruptor.EventHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Disruptor事件处理器（消费者）。
 * 直接将生成的UUID通过Netty上下文返回给客户端。
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-11 10:21:11
 */
public class UuidEventHandler implements EventHandler<UuidEvent> {
    private static final Logger logger = LoggerFactory.getLogger(UuidEventHandler.class);
    private static long requestIdCounter = 0;

    @Override
    public void onEvent(UuidEvent event, long sequence, boolean endOfBatch) {
        try {
            String uuid = event.getUuid();
            ChannelHandlerContext ctx = event.getCtx();
            long requestId = event.getRequestId();

            if (ctx != null && ctx.channel().isActive()) {
                // 构造HTTP响应
                FullHttpResponse response = new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK,
                        Unpooled.copiedBuffer(uuid, CharsetUtil.UTF_8)
                );
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
                response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

                // 发送响应
                ctx.writeAndFlush(response);
                logger.debug("Request {} completed with UUID: {}", requestId, uuid);
            } else {
                logger.debug("Channel is not active for request {}, UUID: {}", requestId, uuid);
            }
        } catch (Exception e) {
            logger.error("Error handling UUID event", e);
        } finally {
            // 清理事件数据
            event.clear();
        }
    }

    public static synchronized long nextRequestId() {
        return ++requestIdCounter;
    }

}
